#!/bin/sh -e

if [ -x /usr/bin/logger ]; then
    LOGGER="/usr/bin/logger -s -p daemon.info -t ipsettables"
else
    LOGGER=echo
fi

case "$2" in
    up)
        if [ ! -r /etc/ipset.rules ]; then
            ${LOGGER} "No ipset rules exist to restore."
            return
        fi
        if [ ! -x /usr/sbin/ipset ]; then
            ${LOGGER} "No program exists to restore ipset rules."
            return
        fi
        ${LOGGER} "Restoring ipset rules"
        /usr/sbin/ipset -R < /etc/ipset.rules

        if [ ! -r /etc/iptables.rules ]; then
            ${LOGGER} "No iptables rules exist to restore."
            return
        fi
        if [ ! -x /sbin/iptables-restore ]; then
            ${LOGGER} "No program exists to restore iptables rules."
            return
        fi
        ${LOGGER} "Restoring iptables rules"
        /sbin/iptables-restore -c < /etc/iptables.rules
        ;;

    down)
        if [ ! -x /usr/sbin/ipset ]; then
            ${LOGGER} "No program exists to save ipset rules."
            return
        fi
        ${LOGGER} "Saving ipset rules."
        /usr/sbin/ipset -S > /etc/ipset.rules

        if [ ! -x /sbin/iptables-save ]; then
            ${LOGGER} "No program exists to save iptables rules."
            return
        fi
        ${LOGGER} "Saving iptables rules."
        /sbin/iptables-save -c > /etc/iptables.rules
        ;;

    *)
        ;;
esac
